package com.mengdie.shuidi.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.api.network.StringDialogCallback;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.ui.interfaces.VerifyHelper;
import com.mengdie.shuidi.utils.DeviceUuidFactory;
import com.mengdie.shuidi.utils.ToastUtil;
import com.mengdie.shuidi.utils.common.MD5Util;
import com.mengdie.shuidi.utils.common.RegularUtils;
import com.mengdie.shuidi.widgets.ButtonTimer;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/13.
 */

public class BindPhoneActivity extends BaseActivity {


    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.et_bind_phone)
    EditText mEtBindPhone;
    @Bind(R.id.et_bind_code)
    EditText mEtBindCode;
    @Bind(R.id.bt_bind_code)
    ButtonTimer mBtBindCode;
    @Bind(R.id.et_bind_local_code)
    EditText mEtBindLocalCode;
    @Bind(R.id.iv_bind_local_code)
    ImageView mIvBindLocalCode;
    @Bind(R.id.tv_bind_submit)
    TextView mTvBindSubmit;
    @Bind(R.id.iv_bind_verfiy)
    ImageView mIvBindVerfiy;
    @Bind(R.id.et_bind_verfiy)
    EditText mEtBindVerfiy;
    private String name;
    private String phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone);
        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            name = bundle.getString("name");
        } else {
            name = MDAccountMgr.getInstance().getLoginName();
        }

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    public void init() {
        mTvGenericTitle.setText("绑定手机号");
    }

    @OnClick({R.id.rl_generic_back, R.id.bt_bind_code, R.id.iv_bind_local_code, R.id.tv_bind_submit, R.id.iv_bind_verfiy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_generic_back:
                onBackPressed();
                break;
            case R.id.bt_bind_code:
                phone = mEtBindPhone.getText().toString();
                String verfiy = mEtBindVerfiy.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.showToast(getResources().getString(R.string.et_is_phone_empty));
                } else {
                    if (RegularUtils.isMobileExact(phone)) {
                        getCode(phone, verfiy);
                    } else {
                        ToastUtil.showToast("手机号格式不正确");
                    }
                }
                break;
            case R.id.iv_bind_local_code:

                break;
            case R.id.iv_bind_verfiy:

                break;
            case R.id.tv_bind_submit:
                phone = mEtBindPhone.getText().toString();
                String code = mEtBindCode.getText().toString();
                if (TextUtils.isEmpty(phone) && TextUtils.isEmpty(code)) {
                    ToastUtil.showToast(getResources().getString(R.string.et_is_phone_empty));
                } else {
                    if (RegularUtils.isMobileExact(phone)) {
                        setPhone(phone, code);
                    } else {
                        ToastUtil.showToast("手机号格式不正确");
                    }
                }
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        VerifyHelper.getImgVerify(mIvBindVerfiy);
    }

    public void getCode(String phone, String verfiy) {
        HashMap<String, String> map = new HashMap<>();
        map.put("num", phone);
        map.put("code", "rst_pass");
        map.put("verify", verfiy);
        JSONObject json = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this))
                .post(AppContext.getInstance().getBaseUrl() + "account/get_code_new")
                .tag(BindPhoneActivity.this)
                .upJson(json.toString())
                .execute(new StringDialogCallback(BindPhoneActivity.this, "加载中...", true) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            mBtBindCode.setTimes(60);
                            if (!mBtBindCode.isRun()) {
                                mBtBindCode.beginRun();
                                mBtBindCode.setEnabled(false);
                            }
                            ToastUtil.showToast(baseModel.getMsg());
                        } else {
                            VerifyHelper.getImgVerify(mIvBindVerfiy);
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });

    }

    public void setPhone(String phone, String code) {
        HashMap map = new HashMap();
        map.put("version", AppContext.version);
        map.put("username", name);
        map.put("phone", phone);
        map.put("phone_code", code);
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        JSONObject json = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this)).post(AppContext.getInstance().getBaseUrl() + "account/set_phone")
                .tag(BindPhoneActivity.this)
                .upJson(json.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        Logger.e("绑定手机号: " + baseModel.toString());
                        if (baseModel.getRet().equals("0")) {
                            if (MDUserMgr.getInstance().getPhone().equals("")) {
                                Intent bind = new Intent(BindPhoneActivity.this, BindPhoneSuccessActivity.class);
                                startActivity(bind);
                                finish();
                            } else {
                                ToastUtil.showToast("换绑成功");
                                finish();
                            }
                        } else {
                            VerifyHelper.getImgVerify(mIvBindVerfiy);
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }

                });
    }


}
